package com.qys.livesMall.anchor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.anchor.constants.enums.AnchorSellTaskStatus;
import com.qys.livesMall.anchor.mapper.AnchorSellTaskMapper;
import com.qys.livesMall.anchor.model.dto.task.app.SellLivesApplySaveDTO;
import com.qys.livesMall.anchor.model.dto.task.app.SellTaskAnchorPageDTO;
import com.qys.livesMall.anchor.model.dto.task.app.SellTaskHallPageDTO;
import com.qys.livesMall.anchor.model.dto.task.sys.SysSellTaskAnchorPageDTO;
import com.qys.livesMall.anchor.model.entity.AnchorLivesSession;
import com.qys.livesMall.anchor.model.entity.AnchorSellLivesApply;
import com.qys.livesMall.anchor.model.entity.AnchorSellTask;
import com.qys.livesMall.anchor.model.entity.H2Anchor;
import com.qys.livesMall.anchor.model.vo.task.app.AppSellLivesApplyDetailVO;
import com.qys.livesMall.anchor.model.vo.task.app.AppSellTaskAnchorPageVO;
import com.qys.livesMall.anchor.model.vo.task.app.SellTaskHallPageVO;
import com.qys.livesMall.anchor.model.vo.task.app.child.SellLivesChild;
import com.qys.livesMall.anchor.model.vo.task.sys.SysSellTaskAnchorPageVO;
import com.qys.livesMall.anchor.service.AnchorLivesSessionService;
import com.qys.livesMall.anchor.service.AnchorSellLivesApplyService;
import com.qys.livesMall.anchor.service.AnchorSellTaskService;
import com.qys.livesMall.anchor.service.H2AnchorService;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.common.enums.CommonPassFlag;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.shop.dao.H2ShopBaseDao;
import com.qys.livesMall.shop.mapper.H2ShopLevelMapper;
import com.qys.livesMall.shop.modal.entity.*;
import com.qys.livesMall.shop.service.ShopGoodsInfoService;
import com.qys.livesMall.shop.service.ShopSellTaskProductService;
import com.qys.livesMall.shop.service.ShopSellTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 主播接取带货任务表 服务实现类
 * </p>
 *
 * @author
 * @since 2023-06-16
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AnchorSellTaskServiceImpl extends ServiceImpl<AnchorSellTaskMapper, AnchorSellTask> implements AnchorSellTaskService {


    private final ShopSellTaskProductService taskProductService;
    private final ShopSellTaskService shopSellTaskService;
    private final H2ShopBaseDao h2ShopBaseDao;
    private final H2AnchorService anchorService;
    private final AnchorSellLivesApplyService anchorSellLivesApplyService;
    private final ShopGoodsInfoService goodsInfoService;
    private final H2ShopLevelMapper shopLevelMapper;
    private final AnchorLivesSessionService livesSessionService;
    private final IH2AppUserService appUserService;

    @Override
    public Page<SellTaskHallPageVO> taskHallPage(SellTaskHallPageDTO queryDTO) {
        H2Anchor anchor = anchorService.checkAnchorsAndReturn(SecurityUtils.getUserId());

        //主播接取任务Id集合
        List<Long> shopSellTaskIdList = baseMapper.receivedList(null);
        Page<SellTaskHallPageVO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        //排除主播截取任务
        page = baseMapper.taskHallListByAppPage(page, queryDTO, shopSellTaskIdList);
        List<Long> shopBaseIdList = page.getRecords().stream().map(SellTaskHallPageVO::getShopBaseId).toList();
        if (shopBaseIdList.size() == 0) {
            return new Page<>();
        }
        List<H2ShopBase> list = h2ShopBaseDao.list(Wrappers.<H2ShopBase>lambdaQuery().in(H2ShopBase::getId, shopBaseIdList));
        Map<Long, H2ShopBase> shopBaseIdMap = list.stream().collect(Collectors.toMap(H2ShopBase::getId, item -> item));
        Long shopBaseId = h2ShopBaseDao.queryShopBaseIdByUserId(SecurityUtils.getUserId());
        page.getRecords().forEach(e -> {
            Integer shopLevelId = shopBaseIdMap.get(e.getShopBaseId()).getShopLevelId();
            e.setShopLevelId(shopLevelId);
            H2ShopLevel shopLevel = shopLevelMapper.selectById(shopLevelId);
            e.setShopLevelName(shopLevel==null?null:shopLevel.getName());
            e.setMyFlag(e.getShopBaseId().equals(shopBaseId));
            Long count = shopSellTaskService.count(Wrappers.<ShopSellTask>lambdaQuery().eq(ShopSellTask::getShopBaseId, shopBaseId));
            e.setTaskNum(count);
            e.setReceiveFlag(checkReceiveFlag(e.getId(), anchor.getId()));
        });
        return page;
    }

    /**
     * 主播接单
     */
    @Override
    public void receiveShopSellTask(Long sellTaskId) {
        H2Anchor anchor = anchorService.checkAnchorsAndReturn(SecurityUtils.getUserId());
        if(Constants.YesNoInt.NO.equals(anchor.getTaskAuthority())){
            throw new QysException(MessageUtils.message("no.task.permission"));
        }

        ShopSellTask task = shopSellTaskService.checkSellTask(sellTaskId);
        if (checkReceiveFlag(sellTaskId, anchor.getId())) {
            throw new QysException(MessageUtils.message("请勿重复接单"));
        }
        AnchorSellTask anchorSellTask = new AnchorSellTask();
        anchorSellTask.setShopName(task.getShopName());
        anchorSellTask.setShopBaseId(task.getShopBaseId());
        anchorSellTask.setAnchorId(anchor.getId());
        anchorSellTask.setShopSellTaskId(sellTaskId);
        anchorSellTask.setAnchorName(anchor.getAnchorName());
        anchorSellTask.setCreateTime(LocalDateTime.now());
        anchorSellTask.setStatus(AnchorSellTaskStatus.未申请.getStatus());//未申请开播
        baseMapper.insert(anchorSellTask);
    }

    @Override
    public Page<AppSellTaskAnchorPageVO> anchorSellTaskList(SellTaskAnchorPageDTO queryDTO) {
        Page<AppSellTaskAnchorPageVO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        page = baseMapper.anchorSellTaskListByAppPage(page, queryDTO);
        if (page.getRecords().size() == 0) {
            return page;
        }
        List<Long> sellTaskIdList = page.getRecords().stream().map(AppSellTaskAnchorPageVO::getShopSellTaskId).toList();
        List<ShopSellTask> list = shopSellTaskService.list(Wrappers.<ShopSellTask>lambdaQuery().in(ShopSellTask::getId, sellTaskIdList));
        Map<Long, ShopSellTask> idSellTaskMap = list.stream().collect(Collectors.toMap(ShopSellTask::getId, item -> item));
        page.getRecords().forEach(e -> {
            ShopSellTask task = idSellTaskMap.get(e.getShopSellTaskId());
            e.setTaskBenefitType(task.getTaskBenefitType());
            e.setTaskProductName(task.getTaskProductName());
            e.setTaskInfo(task.getTaskInfo());
            e.setTaskGoal(task.getTaskGoal());
            e.setTaskName(task.getTaskName());
        });
        return page;
    }

    @Override
    public Page<SysSellTaskAnchorPageVO> anchorSysSellTaskList(SysSellTaskAnchorPageDTO queryDTO) {
        Page<SysSellTaskAnchorPageVO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        page = baseMapper.anchorSellTaskListBySysPage(page, queryDTO);
        if (page.getRecords().size() == 0) {
            return page;
        }
        List<Long> sellTaskIdList = page.getRecords().stream().map(SysSellTaskAnchorPageVO::getShopSellTaskId).toList();
        List<ShopSellTask> list = shopSellTaskService.list(Wrappers.<ShopSellTask>lambdaQuery().in(ShopSellTask::getId, sellTaskIdList));
        Map<Long, ShopSellTask> idSellTaskMap = list.stream().collect(Collectors.toMap(ShopSellTask::getId, item -> item));
        page.getRecords().forEach(e -> {
            ShopSellTask task = idSellTaskMap.get(e.getShopSellTaskId());
            e.setTaskBenefitType(task.getTaskBenefitType());
            e.setTaskProductName(task.getTaskProductName());
            e.setTaskInfo(task.getTaskInfo());
            e.setTaskGoal(task.getTaskGoal());
            e.setTaskName(task.getTaskName());
        });
        return page;
    }


    @Override
    public AppSellLivesApplyDetailVO sellLivesDetail(Long anchorSellTaskId) {
        AppSellLivesApplyDetailVO vo = new AppSellLivesApplyDetailVO();
        AnchorSellTask anchorSellTask = baseMapper.selectById(anchorSellTaskId);
        if (null == anchorSellTask) {
            throw new QysException("请检查ID");
        }
        H2Anchor h2Anchor = anchorService.checkAnchorsAndReturn(SecurityUtils.getUserId());
        List<Long> list = taskProductService.listGoodsInfoIdBySellTaskId(anchorSellTask.getShopSellTaskId());
        List<ShopGoodsInfo> infoList = goodsInfoService.list(Wrappers.<ShopGoodsInfo>lambdaQuery()
                .in(ShopGoodsInfo::getId, list));
        List<SellLivesChild> sellLivesChildren = BeanUtil.copyToList(infoList, SellLivesChild.class);
        //设置带货数量
        for (SellLivesChild sellLivesChild : sellLivesChildren) {
            ShopSellTaskProduct one = taskProductService.getOne(Wrappers.<ShopSellTaskProduct>lambdaQuery()
                    .eq(ShopSellTaskProduct::getShopSellTaskId, anchorSellTask.getShopSellTaskId())
                    .eq(ShopSellTaskProduct::getShopGoodsInfoId, sellLivesChild.getId()));
            sellLivesChild.setQuantitySold(one == null ? null : one.getQuantitySold());
        }
        vo.setGoodsChildList(sellLivesChildren);
        AnchorSellLivesApply sellLivesApply = anchorSellLivesApplyService.checkRepeat(anchorSellTaskId, h2Anchor.getId());
        ShopSellTask sellTask = shopSellTaskService.getById(anchorSellTask.getShopSellTaskId());
        vo.setTaskStartTime(sellTask.getTaskStartTime());
        vo.setTaskEndTime(sellTask.getTaskEndTime());
        vo.setTaskName(sellTask.getTaskName());
        vo.setAnchorName(anchorSellTask.getAnchorName());
        vo.setNickName(appUserService.getById(h2Anchor.getUserId()).getNickName());
        vo.setLivesStatus(sellLivesApply == null ? -1 : sellLivesApply.getPassFlag());
        vo.setStartLivesTime(sellLivesApply == null ? null : sellLivesApply.getStartLivesTime());
        vo.setApplyTime(sellLivesApply == null ? null : sellLivesApply.getCreateTime());
        vo.setShopName(anchorSellTask.getShopName());
        vo.setLivesSessionName(sellLivesApply == null ? null : sellLivesApply.getLivesSessionName());

        if(vo.getLivesStatus() == 2){
            AnchorLivesSession one = livesSessionService.getOne(Wrappers.<AnchorLivesSession>lambdaQuery()
                    .eq(AnchorLivesSession::getAnchorId, h2Anchor.getId())
                    .eq(AnchorLivesSession::getAnchorSellTaskId, anchorSellTaskId).eq(AnchorLivesSession::getLivesStatus, (byte) 3)
                    .orderByDesc(AnchorLivesSession::getId)
                    .last("limit 1"));
            if(one != null){
                vo.setPlatformSettlement(one.getPlatformSettlement());
                vo.setRemark(one.getRemark());
                if(one.getPlatformSettlement() == null){
                    vo.setTaskStatus((byte)2);
                } else if(one.getPlatformSettlement() == 0){
                    vo.setTaskStatus((byte)3);
                } else if(one.getPlatformSettlement() == 1||one.getPlatformSettlement() == 2){
                    vo.setTaskStatus((byte)4);
                }
            }
        }

        return vo;
    }

    /**
     * 申请开播
     *
     * @param saveDTO
     */
    @Override
    public void applySellLives(SellLivesApplySaveDTO saveDTO) {
        H2Anchor h2Anchor = anchorService.checkAnchorsAndReturn(SecurityUtils.getUserId());

        //判断是否重复申请
        AnchorSellLivesApply livesApply = anchorSellLivesApplyService.checkRepeat(saveDTO.getAnchorSellTaskId(), h2Anchor.getId());
        if (null != livesApply) {
            CommonPassFlag.checkStatus(livesApply.getPassFlag(), CommonPassFlag.审核未通过);
            livesApply.setStartLivesTime(saveDTO.getStartLivesTime());
            livesApply.setPassFlag(CommonPassFlag.审核中.getStatus());
            anchorSellLivesApplyService.updateById(livesApply);
            return;
        }
        AnchorSellTask anchorSellTask = baseMapper.selectById(saveDTO.getAnchorSellTaskId());
        if (null == anchorSellTask) {

            throw new QysException(MessageUtils.message("请检查主播带货任务编号"));
        } else {
            anchorSellTask.setStatus(AnchorSellTaskStatus.未申请.getStatus());
            baseMapper.updateById(anchorSellTask);
        }
        AnchorSellLivesApply sellLivesApply = new AnchorSellLivesApply();
        sellLivesApply.setPassFlag(CommonPassFlag.审核中.getStatus());
        sellLivesApply.setAnchorSellTaskId(saveDTO.getAnchorSellTaskId());
        sellLivesApply.setStartLivesTime(saveDTO.getStartLivesTime());
        sellLivesApply.setCreateTime(LocalDateTime.now());
        sellLivesApply.setAnchorId(anchorSellTask.getAnchorId());
        sellLivesApply.setAnchorName(anchorSellTask.getAnchorName());
        sellLivesApply.setLivesSessionName(saveDTO.getLivesSessionName());
        anchorSellLivesApplyService.save(sellLivesApply);
    }

    /**
     * 判断主播是否接过单
     */
    private boolean checkReceiveFlag(Long shopSellTaskId, Long anchorId) {
        return baseMapper.selectCount(Wrappers.<AnchorSellTask>lambdaQuery()
                .eq(AnchorSellTask::getShopSellTaskId, shopSellTaskId)
                .eq(AnchorSellTask::getAnchorId, anchorId)) > 0;
    }


}
